package com.alipay.rebate.shop.helper;

import com.alipay.rebate.shop.constants.LuckyMonCouponConstant;
import com.alipay.rebate.shop.dao.mapper.CouponGetRecordMapper;
import com.alipay.rebate.shop.dao.mapper.LuckyMoneyCouponMapper;
import com.alipay.rebate.shop.dao.mapper.OrdersMapper;
import com.alipay.rebate.shop.dao.mapper.UserIncomeMapper;
import com.alipay.rebate.shop.dao.mapper.UserMapper;
import com.alipay.rebate.shop.dao.mapper.WithDrawMapper;
import com.alipay.rebate.shop.model.CouponGetRecord;
import com.alipay.rebate.shop.model.LuckyMoneyCoupon;
import com.alipay.rebate.shop.model.UserIncome;
import com.alipay.rebate.shop.pojo.user.customer.UserCouponRsp;
import com.alipay.rebate.shop.utils.ListUtil;
import java.math.BigDecimal;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component
public class LuckyMoneyHelper {

  private Logger logger = LoggerFactory.getLogger(LuckyMoneyHelper.class);
  @Resource
  private CouponGetRecordMapper couponGetRecordMapper;
  @Resource
  private WithDrawMapper withDrawMapper;
  @Resource
  private UserMapper userMapper;
  @Resource
  private UserIncomeMapper userIncomeMapper;
  @Resource
  private OrdersMapper ordersMapper;
  @Resource
  private LuckyMoneyCouponMapper luckyMoneyCouponMapper;


  public void openLuckyMoneyCouponIfNeed(Long userId,Integer type,List<UserCouponRsp> userCouponRsps, boolean flag){
    // 获取用户拿到的红包卷
    if(!flag){
       // 获取到用户的红包卷
       userCouponRsps = couponGetRecordMapper.selectCouponDetailByUserId(userId);
    }
    if(ListUtil.isEmptyList(userCouponRsps)){
      return;
    }
    logger.debug("userCouponRsps is : {}",userCouponRsps);
    // 根据金额进行排序
    Collections.sort(userCouponRsps, Comparator.comparing(UserCouponRsp::getAmountOfMoney));
    // 过滤掉已经使用和不符合类型的红包卷
    userCouponRsps = userCouponRsps.stream().filter(userCouponRsp -> userCouponRsp.getIsUse() == 0
        && userCouponRsp.getConditionType().equals(type)).collect(Collectors.toList());
    openLuckyMoneyCouponIfNeed(userId,type,userCouponRsps);
  }
  private void openLuckyMoneyCouponIfNeed(Long userId,Integer type,List<UserCouponRsp> userCouponRsps){
    logger.debug("userId and type is : {},{}",userId,type);
    logger.debug("userCouponRsps : {}",userCouponRsps);
    if (!ListUtil.isEmptyList(userCouponRsps)){
      // 每次只促发一个，并且是满足条件金额最大那个
      for(int i=userCouponRsps.size() -1; i>=0; i--){
        Date now = new Date();
        UserCouponRsp userCouponRsp = userCouponRsps.get(i);
        if (now.getTime() <= userCouponRsp.getEndTime().getTime()){
          // 返利满
          if (isOrdersReawrdType(type,userCouponRsp)){
            BigDecimal orderRewardMoney = userIncomeMapper.selectOrderRewardIncomeMoneyByUserId(userId);
            logger.debug("orderRewardMoney is : {}",orderRewardMoney);
            if(orderRewardMoney != null && orderRewardMoney.compareTo(userCouponRsp.getConditionMoney())>=0){
              doOpenCoupon(userId,userCouponRsp);
              break;
            }
          }
          // 提现满
          if (isWithDrawType(type,userCouponRsp)){
            BigDecimal withdrawMoney = withDrawMapper.selectWithDrawMoneyByUserId(userId);
            logger.debug("withdrawMoney is : {}",withdrawMoney);
            if(withdrawMoney != null && withdrawMoney.compareTo(userCouponRsp.getConditionMoney())>=0){
              doOpenCoupon(userId,userCouponRsp);
              break;
            }
          }
          // 购买满
          if (isPaidType(type,userCouponRsp)){
            BigDecimal paidMoney = ordersMapper.selectPaidMoneyByUserId(userId);
            logger.debug("paidMoney is : {}",paidMoney);
            if(paidMoney != null && paidMoney.compareTo(userCouponRsp.getConditionMoney())>=0){
              doOpenCoupon(userId,userCouponRsp);
              break;
            }
          }
        }
      }
    }
  }

  private boolean isWithDrawType(Integer type,UserCouponRsp userCouponRsp){
    return LuckyMonCouponConstant.CONDITION_TYPE_WITHDRAW_MONEY.equals(type) &&
        type.equals(userCouponRsp.getConditionType());
  }

  private boolean isOrdersReawrdType(Integer type,UserCouponRsp userCouponRsp){
    return LuckyMonCouponConstant.CONDITION_TYPE_ORDER_REWARD.equals(type) &&
        type.equals(userCouponRsp.getConditionType());
  }

  private boolean isPaidType(Integer type,UserCouponRsp userCouponRsp){
    return LuckyMonCouponConstant.CONDITION_TYPE_PAID_MONEY.equals(type) &&
        type.equals(userCouponRsp.getConditionType());
  }

  private void doOpenCoupon(Long userId, UserCouponRsp userCouponRsp){
    userMapper.plusUserAM(userCouponRsp.getAmountOfMoney(),userId);
    UserIncome userIncome =  UserIncomeBuilder
        .buildLuckyMoneyUserIncome(userCouponRsp.getAmountOfMoney(),userId);
    userIncomeMapper.insertSelective(userIncome);
    CouponGetRecord nGetRecord = new CouponGetRecord();
    nGetRecord.setId(userCouponRsp.getId());
    nGetRecord.setIsUse(1);
    couponGetRecordMapper.updateByPrimaryKeySelective(nGetRecord);
  }

  public void giveLuckyMoneyCoupon(Long userId){
    List<LuckyMoneyCoupon> luckyMoneyCoupons = luckyMoneyCouponMapper.selectCurrentUseCoupon();
    if(!ListUtil.isEmptyList(luckyMoneyCoupons)){
      luckyMoneyCoupons.forEach(luckyMoneyCoupon -> {
        CouponGetRecord couponGetRecord = UserBuilder.buildCouponGetRecord(userId,luckyMoneyCoupon);
        Date now = new Date();
        if (couponGetRecord != null && now.getTime() <= luckyMoneyCoupon.getEndTime().getTime()){
          couponGetRecordMapper.insertSelective(couponGetRecord);
          luckyMoneyCouponMapper.decreaseStockByOne(luckyMoneyCoupon.getId());
        }
      });
    }
  }

}
